package com.epam.client.backingbeans;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.enterprise.event.Event;
import javax.faces.model.SelectItem;
import javax.inject.Inject;
import javax.transaction.UserTransaction;

import org.apache.log4j.Logger;

import com.epam.DAO.CarDAO;
import com.epam.DAO.ClientDAO;
import com.epam.DAO.RequestDAO;
import com.epam.entity.Car;
import com.epam.entity.Client;
import com.epam.entity.Request;
import com.epam.entity.Status;
import com.epam.events.Notifications;
import com.epam.events.TypedAnnotationLiteral;
import com.epam.utils.JsfUtil;

public class NewRequestBean {

	@EJB
	private RequestDAO requestDAO;
	@EJB
	private CarDAO carDAO;
	@EJB
	private ClientDAO clientDAO;
	@Resource
	private UserTransaction ut;
	@Inject
	private Event<Request> eventProcessor;
	private List<SelectItem> cars;
	private Request request;
	private static Logger logger = Logger.getLogger(NewRequestBean.class);

	public NewRequestBean() {
		request = new Request();
	}

	public Request getRequest() {
		return request;
	}

	public void setRequest(Request request) {
		this.request = request;
	}

	public List<SelectItem> getCars() {
		cars = JsfUtil.getSelectItems(carDAO.getAvaliableCars());
		return cars;
	}

	public String createRequest() {

		try {
			if (request.getBeginDate().before(request.getEndDate())
					&& request.getBeginDate().after(new Date())) {
				try {
					ut.begin();

					Client client = clientDAO.read();
					Car car = request.getCar();
					car.setIsAvaliable(false);
					carDAO.update(car);

					request.setClient(client);
					request.setStatus(Status.NEW);
					requestDAO.create(request);

					eventProcessor.select(new TypedAnnotationLiteral(Notifications.CREATED)).fire(request);
										
					JsfUtil.addMessage("new_request_form:beginDate",
							"Request successfully created");

					ut.commit();
					request = new Request();
					return "success";
				} catch (Exception e) {
					ut.rollback();
				}
			}
		} catch (Exception e) {
			logger.error(e.toString());
		}
		JsfUtil.addMessage("new_request_form:beginDate", "Check the input data");
		return "fail";
	}
}